<template>
  <!-- 计划维修明细表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      :width="!props.isReadonly ? '900px' : '750px'"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="120"
      >
        <div>
          <el-row>
            <el-col :span="12">
              <el-form-item label="设备" prop="propertyId" style="width: 100%">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.propertyId"
                  placeholder="请选择设备"
                  clearable
                />
                <span v-else>{{ formData.propertyId }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="位置" prop="propertyId" style="width: 100%">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.propertyId"
                  placeholder="请输入位置"
                  disabled
                  clearable
                />
                <span v-else>{{ formData.propertyId }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="设备种类"
                prop="propertyId"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.propertyId"
                  placeholder="请输入设备种类"
                  disabled
                  clearable
                />
                <span v-else>{{ formData.propertyId }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="品牌型号"
                prop="propertyId"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.propertyId"
                  placeholder="请输入品牌型号"
                  disabled
                  clearable
                />
                <span v-else>{{ formData.propertyId }}</span>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item
                label="计划开始时间"
                prop="planStartTime"
                style="width: 100%"
              >
                <!-- <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.planStartTime"
                  placeholder="请输入计划开始时间"
                  clearable
                /> -->
                <el-date-picker
                  style="width: 500px"
                  v-if="!props.isReadonly"
                  v-model="formData.planStartTime"
                  type="date"
                  placeholder="请输入计划开始时间"
                  format="YYYY/MM/DD"
                  value-format="YYYY-MM-DD"
                />
                <span v-else>{{ formData.planStartTime }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="计划时间(小时)"
                prop="planHour"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.planHour"
                  placeholder="请输入计划时间(小时)"
                  clearable
                />
                <span v-else>{{ formData.planHour }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="计划维修内容"
                prop="remarks"
                style="width: 100%"
              >
                <el-input
                  maxlength="255"
                  show-word-limit
                  type="textarea"
                  v-if="!props.isReadonly"
                  :autosize="{ minRows: 4, maxRows: 5 }"
                  v-model="formData.remarks"
                  placeholder="请输入计划维修内容"
                  clearable
                />
                <span v-else>{{ formData.remarks }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
          v-if="!props.isReadonly"
        >
          <h4 class="mb-[20px] mt-[20px]">备件清单</h4>
          <el-button
            type="success"
            plain
            @click="handleAdd"
            v-if="!props.isReadonly"
          >
            <i-ep-plus />
            新增
          </el-button>
        </div>
        <div class="formTable">
          <el-table
            :data="formData.details"
            style="width: 100%"
            :key="Math.random"
            max-height="240px"
            overflow-y="auto"
            border
          >
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="100"
            >
            </el-table-column>
            <el-table-column label="备件" props="sparePartId" min-width="150">
              <template #default="{ $index, row }">
                <span
                  >{{ row.sparePartName }}{{ row.sparePartName ? "-" : ""
                  }}{{ row.sparePartCode }}</span
                >
              </template>
            </el-table-column>
            <el-table-column
              label="备件类型"
              props="sparePartType"
              min-width="150"
            >
              <template #default="{ $index, row }">
                <span>{{ row.sparePartType }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="备件数量"
              props="sparePartNumber"
              min-width="150"
            >
              <template #default="{ $index, row }">
                <span>{{ row.sparePartNumber }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="备件单位"
              props="sparePartUnit"
              min-width="150"
            >
              <template #default="{ $index, row }">
                <span>{{ row.sparePartUnit }}</span>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="100"
              v-if="!props.isReadonly"
            >
              <template #default="scope">
                <el-button
                  :disabled="formData.details.length < 2"
                  type="danger"
                  link
                  @click.stop="handleDelete(scope.$index)"
                >
                  <i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定
          </el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "EAMEAMREPAIRPLANDETAILADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  version: "",
  planId: "",
  propertyId: "",
  planStartTime: "",
  planHour: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
  details: [
    {
      id: "",
      planDetailId: "",
      sparePartId: "",
      sparePartNumber: "",
      version: "",
      remarks: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      enabled: "",
      deleted: "",
    },
  ],
});

/** rules规则 */
const rules = reactive({
  version: [],
  propertyId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  planStartTime: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  planHour: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  enabled: [],
  sonplanDetailId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  sonsparePartId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  sonsparePartNumber: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
});

const isValidated = ref(false);
/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

const details = {
  id: "",
  planDetailId: "",
  sparePartId: "",
  sparePartNumber: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [JSON.parse(JSON.stringify(details))];
  formData.id = "";
  formData.version = "";
  formData.planId = "";
  formData.propertyId = "";
  formData.planStartTime = "";
  formData.planHour = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
}

const loading = ref(false);

/** 计划维修明细保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/eam/eamrepairplandetail/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

async function getdetails() {
  let sondetails = await request({
    url: "/eam/eamrepairplandetail/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
}
</script>

<style lang="scss" scoped>
.formTable {
  :deep(.el-form-item) {
    margin: 0 0 13px 0 !important;
    width: 100%;
  }
}

:deep(.el-dialog .formTable .el-table .el-form-item) {
  padding: 11px 0 0 0 !important;
}
:deep(.el-dialog .formTable .el-table .el-form-item__error) {
  font-size: 11px !important;
}

:deep(.el-dialog .formTable .el-table) {
  // .cell.el-tooltip {
  //   padding: 0 15px;
  // }

  // .el-table__body td.el-table__cell {
  //   padding: 20;
  // }
  // .cell.el-tooltip {
  //   padding: 5px;
  // }
  .el-table__body td.el-table__cell {
    // padding: 5px !important;
    padding: 0 !important;
  }
}

:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 160px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 180px;
}
</style>
